package cn.enited.devtools.apiaggregator.startup;

import cn.enited.devtools.apiaggregator.api.cache.ApiCacheManager;
import cn.enited.devtools.apiaggregator.service.ApiConfService;
import cn.hutool.core.date.StopWatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Set;

@Slf4j
@Component
public class ApplicationStartupListener implements ApplicationListener<ContextRefreshedEvent> {

    private ApiCacheManager apiCacheManager;

    private ApiConfService apiConfService;

    private boolean localCacheLoadEager;

    @Autowired
    public void setApiCacheManager(ApiCacheManager apiCacheManager) {
        this.apiCacheManager = apiCacheManager;
    }

    @Autowired
    public void setApiConfService(ApiConfService apiConfService) {
        this.apiConfService = apiConfService;
    }

    @Value("${local-cache.load.eager:false}")
    public void setLocalCacheLoadEager(boolean localCacheLoadEager) {
        this.localCacheLoadEager = localCacheLoadEager;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext app = event.getApplicationContext();
        // 只在Spring容器启动时执行一次，如果不加判断那么spring mvc容器启动时还会再执行一次就出错了
        if (Objects.isNull(app.getParent())) {
            log.info("============Spring容器启动==============");
            if (localCacheLoadEager) {
                log.info(">>>开始初始化本地缓存<<<");
                StopWatch timeCounter = new StopWatch();
                timeCounter.start("init-local-cache");
                Set<String> completableApiNames = apiConfService.findAllCompletableApiNames();
                apiCacheManager.init(completableApiNames);
                timeCounter.stop();
                log.info(">>>初始化本地缓存完毕，用时:{}秒<<<", timeCounter.getTotalTimeSeconds());
            }
        }

    }
}
